clear all
set more off

do "set_path.do"

global cipdata 			"${datadir}cip_all_both.dta"
global crspdata			"${datadir}treasury/crsp_long_daily.dta"

global file_debt_natl	"${datadir}other/govt_debt_db_m.dta"
global file_gdp_latest	"${datadir}other/gdp.dta"
global file_gdp_haver	"${datadir}other/haver_gdp.dta"

global temp_debt		"${tempdir}debt_q.dta"
global temp_debt_us		"${tempdir}debt_q_us.dta"
global temp_vix_q		"${tempdir}vix_q.dta"
global temp_crsp		"${tempdir}crsp.dta"


***** I. Pre-process other data *****

*** I.1. GDP from Haver ***
tempfile f_gdp_haver
use "$file_gdp_haver", clear
gen quarter = qofd(date)
format quarter %tq
keep quarter currency qgdp_usd
save `f_gdp_haver', replace


*** I.2. GDP from national sources ***
tempfile f_gdp_latest
use "$file_gdp_latest", clear
gen quarter = qofd(date)
format quarter %tq
replace currency = "GBP" if currency == "GBR"

drop date
rename (ngdp ngdp_a) (ngdp_lc ngdp_a_lc)
save `f_gdp_latest', replace


*** I.3. Debt from national sources ***
use "${file_debt_natl}", clear
gen quarter = qofd(month)
format quarter %tq
sort curr month

* Fill quarterly numbers for CHF before 2008 (only annual data available) 
sort group curr month
bys group curr: replace govt_debt_usd = govt_debt_usd[_n-1] if (curr=="CHF") & (yofd(month)<2008) & missing(govt_debt_usd) & !missing(govt_debt_usd[_n-1])
bys group curr: replace govt_debt = govt_debt[_n-1] if (curr=="CHF") & (yofd(month)<2008) & missing(govt_debt) & !missing(govt_debt[_n-1])

replace govt_debt_usd = govt_debt if curr=="USD" & missing(govt_debt_usd)
replace cb_holding_usd = cb_holding if curr=="USD" & missing(cb_holding_usd)

collapse (last) govt_debt govt_debt_usd cb_holding cb_holding_usd cb_percent group, by(curr quarter)

replace group="eme" if group=="em"
rename curr currency

mmerge currency quarter using `f_gdp_haver', type(1:1) unmatch(both)
mmerge currency quarter using `f_gdp_latest', type(1:1) unmatch(both)
drop _merge

* Convert amount to billions
replace govt_debt = govt_debt / 1e9
replace govt_debt_usd = govt_debt_usd / 1e9

replace cb_holding = cb_holding / 1e9
replace cb_holding_usd = cb_holding_usd / 1e9

replace cb_holding = 0 if cb_holding == .
replace cb_holding_usd = 0 if cb_holding_usd == .

replace ngdp_lc = ngdp_lc / 1e9
replace ngdp_a_lc = ngdp_a_lc / 1e9

* Calculate annual GDP
gsort currency -group
bys currency (group): replace group = group[_n-1] if group=="" & group[_n-1]!=""
bys currency (quarter): gen agdp_usd = qgdp_usd + qgdp_usd[_n-1] + qgdp_usd[_n-2] + qgdp_usd[_n-3]

* Debt / GDP
gen dgdp_l = (govt_debt - cb_holding)/ngdp_a_lc
gen gr_dgdp_l = govt_debt / ngdp_a_lc

save ${temp_debt}, replace

* US gross debt / GDP
keep if currency=="USD"
keep quarter dgdp_* gr_dgdp_* agdp_usd

save ${temp_debt_us}, replace


*** I.4. Treasury outstanding by tenor from CRSP ***
tempfile f_crsp
use "$crspdata", clear
gen quarter = qofd(date)
format quarter %tq

* Convert amount to billions
replace tmtotout = tmtotout/1e3
replace tmpubout = tmpubout/1e3

collapse (last) tmtotout tmpubout, by(quarter bucket)
save ${temp_crsp}, replace


*** I.5. VIX ***
use ${datadir}other/vix_usd.dta, clear

gen quarter = qofd(date)
collapse (mean) VIXCLS, by(quarter)
rename VIXCLS vix
format quarter %tq

save ${temp_vix_q}, replace


*** I.6. CDS ***
tempfile _cds_usd
use "${datadir}markit/clean_markit_data.dta", clear
keep if currency=="USD"
save `_cds_usd', replace

tempfile _cds
use "${datadir}markit/clean_markit_data.dta", clear
keep if currency=="CNY"
replace currency="CNH"
append using "${datadir}markit/clean_markit_data.dta"

* 3m data is limited; use 6m instead
keep if inlist(tenor,"1y","2y","3y","5y","10y","20y","30y","6m")
replace tenor="3m" if tenor=="6m"
save `_cds', replace

tempfile _cds_can
import excel "${datadir}bloomberg/can_cds_update.xlsx", sheet(data) firstrow clear
gen currency = "CAD"
drop if missing(date)
save `_cds_can', replace


***** II. Create panel data for regression *****

use $cipdata, clear

* Merge with CDS data
mmerge currency tenor date using `_cds', type(1:1) unmatch(master) ukeep(parspread) urename(parspread cds)
drop _merge

mmerge tenor date using `_cds_usd', type(n:1) unmatch(master) ukeep(parspread) urename(parspread cds_usd)
drop _merge

replace cds = cds * 10000 			// convert to bps
replace cds_usd = cds_usd * 10000	// convert to bps

* CDS data from Bloomberg from 11/17/23 when Markit data are not available; lower than Market by ~5-10bps
mmerge currency tenor date using `_cds_can', type(1:1) unmatch(master) uname(_)
replace cds = _cds if _merge==3 & missing(cds) & !missing(_cds)
drop _*

* Calculate CDS Spread
gen quarter = qofd(date)
format quarter %tq
sort currency date

collapse (last) group (mean) cip_govt cds cds_usd, by(currency quarter tenor)

* Replace spotty 3m CDS with 1y CDS
gen _cds_1y = cds if tenor=="1y"
gen _cds_usd_1y = cds_usd if tenor=="1y"
bys group currency quarter: egen cds_1y = max(_cds_1y)
bys group currency quarter: egen cds_usd_1y = max(_cds_usd_1y)
replace cds = cds_1y if tenor=="3m"
replace cds_usd = cds_usd_1y if tenor=="3m"
drop _*

* Bucket maturities to match CRSP supply data
gen bucket = 1 if tenor=="3m"
replace bucket = 2 if inlist(tenor,"1y","2y")
replace bucket = 3 if inlist(tenor,"3y","5y")
replace bucket = 4 if inlist(tenor,"7y","10y","20y","30y")

* Merge all data sources
mmerge currency quarter using ${temp_debt}, type(n:1) unmatch(master)
mmerge quarter using ${temp_debt_us}, type(n:1) unmatch(master) uname(us_)
mmerge quarter using ${temp_vix_q}, type(n:1) unmatch(both)
mmerge quarter bucket using ${temp_crsp}, type(n:1) unmatch(master)
drop _merge
drop if missing(currency)

* Calculate Statistics 
gen ln_crsp_pgdp = ln(tmtotout/us_agdp_usd)
gen ln_dgdp = ln(dgdp_l)
gen ln_dgdp_us = ln(us_dgdp_l)
gen ln_gr_dgdp = ln(gr_dgdp_l)
gen ln_gr_dgdp_us = ln(us_gr_dgdp_l)

* Label variables
la var ln_dgdp "$\log (\frac{\text{Private holdings of Debt}}{\text{GDP}})_{\text{i}}$"
la var ln_dgdp_us "$\log (\frac{\text{Private holdings of Treasury}}{\text{GDP}})$"

la var ln_gr_dgdp "$\log (\frac{\text{Debt}}{\text{GDP}})_{\text{i}}$"
la var ln_gr_dgdp_us "$\log (\frac{\text{Debt}}{\text{GDP}})_{\text{US}}$"
la var ln_crsp_pgdp "log $(\frac{\text{Debt}}{\text{GDP}})_{\text{US},\text{n}}$"
la var cip_govt "$\Phi$"
la var vix "VIX"
la var cds "$\text{CDS}_{\text{i},\text{n}}$"
la var cds_usd "$\text{CDS}_{\text{US},\text{n}}$"

save ${tempdir}regression_panel.dta, replace


***** III. Supply Regressions *****

use ${tempdir}regression_panel.dta, clear

egen curr_group = group(currency)
egen tenor_group = group(tenor)
egen time_group = group(quarter)
egen panel_id = group(curr_group tenor_group)

xtset panel_id quarter

*** III.1. Tab 6, A4: Total debt ***

capture program drop panelregression_total
program define panelregression_total
	if !missing("`2'") & ("`2'"=="gr") {
		local var1 = "ln_gr_dgdp_us"
		local var2 = "ln_gr_dgdp"
		local fsuffix1 = "gr_"
	}
	else {
		//local var1 = "ln_dgdp_us"
		local var1 = "ln_crsp_pgdp"
		local var2 = "ln_dgdp"
		local fsuffix1 = "pv_"
	}

	capture drop included
	if ("`1'"!="all") {
		gen included = tenor=="`1'"
		local fsuffix2 = "`1'"
	}
	else {
		gen included = inlist(tenor,"3m", "1y", "5y", "10y") 
		local fsuffix2 = "all"
	}

	eststo clear 
	eststo: xtscc cip_govt `var1' `var2' vix if group=="g10" & quarter >= tq(2000q1) & quarter <= tq(2024q4) & included, fe lag(8)
	eststo: xtscc cip_govt `var1' `var2' vix if group=="g10" & quarter >= tq(2000q1) & quarter <= tq(2007q4) & included, fe lag(8)
	eststo: xtscc cip_govt `var1' `var2' vix if group=="g10" & quarter >= tq(2008q1) & quarter <= tq(2024q4) & included, fe lag(8)
	eststo: xtscc cip_govt `var1' `var2' vix cds_usd cds if group=="g10" & quarter >= tq(2008q1) & quarter <= tq(2024q4) & included, fe lag(8)

	esttab est*, k(`var1' `var2' vix cds_usd cds) starlevels(* 0.10 ** 0.05 *** 0.01) b(%7.2f) se label indicate( `r(indicate_fe)') stats(N r2_w,  labels("Observations" "\textit{R}$^{2}$")) title("`1'-`2'")

	esttab est* using "${outdir}tables/panel_regressions_total_`fsuffix1'`fsuffix2'.tex", k(`var1' `var2' vix cds_usd cds) starlevels(* 0.10 ** 0.05 *** 0.01) b(%7.2f) se label indicate( `r(indicate_fe)') stats(N r2_w, fmt(%9.0fc %9.2f) labels("Observations" "\textit{R}$^{2}$")) mlabel("All" "00-07" "08-24" "08-24") title("") substitute(\_ _) prehead("\begin{tabular}{l*{@M}{c}} \hline \hline") prefoot("\hline") postfoot("\hline \hline \end{tabular}") replace
	
end

* Table 6
panelregression_total 5y gr

* Table A3
panelregression_total 1y gr
panelregression_total 10y gr

* Table A4
panelregression_total 5y


*** III.2. Tab 7: Supply by tenor ***

capture program drop panelregression_tenor
program define panelregression_tenor
	if !missing("`2'") & ("`2'"=="gr") {
		local var1 = "ln_gr_dgdp_us"
		local var2 = "ln_gr_dgdp"
		local fsuffix1 = "gr_"
	}
	else {
		local var1 = "ln_dgdp_us"
		local var2 = "ln_dgdp"
		local fsuffix1 = "pv_"
	}

	capture drop included
	if ("`1'"!="all") {
		gen included = tenor=="`1'"
		local fsuffix2 = "`1'"
	}
	else {
		gen included = inlist(tenor,"3m","1y","5y","10y") 
		local fsuffix2 = "all"
	}
			
	est clear 
	eststo: ivreghdfe cip_govt ln_crsp_pgdp ln_gr_dgdp if group=="g10" & quarter >= tq(2000q1) & quarter <= tq(2024q4) & included, absorb(curr_group tenor_group) dkraay(8)
	eststo: ivreghdfe cip_govt ln_crsp_pgdp ln_gr_dgdp if group=="g10" & quarter >= tq(2000q1) & quarter <= tq(2024q4) & included, absorb(curr_group tenor_group quarter) dkraay(8)
	eststo: ivreghdfe cip_govt ln_crsp_pgdp ln_gr_dgdp if group=="g10" & quarter >= tq(2000q1) & quarter <= tq(2007q4) & included, absorb(curr_group tenor_group quarter) dkraay(8)
	eststo: ivreghdfe cip_govt ln_crsp_pgdp ln_gr_dgdp if group=="g10" & quarter >= tq(2008q1) & quarter <= tq(2024q4) & included, absorb(curr_group tenor_group quarter) dkraay(8)
	eststo: ivreghdfe cip_govt ln_crsp_pgdp ln_gr_dgdp cds_usd cds if group=="g10" & quarter >= tq(2008q1) & quarter <= tq(2024q4) & included, absorb(curr_group tenor_group quarter) dkraay(8)
	eststo: ivreghdfe cip_govt ln_crsp_pgdp ln_gr_dgdp cds_usd cds if group=="g10" & quarter >= tq(2010q1) & quarter <= tq(2024q4) & included, absorb(curr_group tenor_group quarter) dkraay(8)

	esttab est*, k(ln_crsp_pgdp ln_gr_dgdp cds_usd cds) starlevels(* 0.10 ** 0.05 *** 0.01) b(%7.2f) se label indicate( `r(indicate_fe)') stats(N r2_w, labels("Observations" "\textit{R}$^{2}$")) title("")

	esttab est* using "${outdir}tables/panel_regressions_tenor_`fsuffix1'`fsuffix2'.tex", k(ln_crsp_pgdp ln_gr_dgdp cds_usd cds) starlevels(* 0.10 ** 0.05 *** 0.01) b(%7.2f) se label indicate( `r(indicate_fe)') stats(N r2, fmt(%9.0fc %9.2f) labels("Observations" "\textit{R}$^{2}$")) mlabel("All" "All" "00-07" "08-24" "08-24" "10-24") title("") substitute(\_ _) prehead("\begin{tabular}{l*{@M}{c}} \hline \hline") prefoot("\hline") postfoot("\hline \hline \end{tabular}") replace
end

panelregression_tenor all gr


*** IV. Fig 7: Tariff Response ***

global TARIFF_DATE	date("4/2/2025", "MDY")

use ${temp_debt}, clear

drop if quarter >= tq(2025q1)
gen _has_debt = 1 if !missing(gr_dgdp_l)
bys group currency _has_debt (quarter): gen _is_last = 1 if _n==_N & _has_debt==1
keep if _is_last==1
drop _*

save ${tempdir}last_dgdp.dta, replace

use $cipdata, clear

* cip_govt before tariffs announcement
gen _cip_govt_p1	= cip_govt if date==${TARIFF_DATE}-1
bys group currency tenor: egen cip_govt_p1 = max(_cip_govt_p1)

* Calculate changes in cip_govt and cds_spread since tariffs announcement
gen day_count = date-${TARIFF_DATE}
keep if day_count>=-30 & day_count<=30

gen cip_govt_ch = cip_govt - cip_govt_p1 if day_count>=0
replace cip_govt_ch = cip_govt_p1 - cip_govt if day_count<0

* Merge with latest debt/gdp data
mmerge currency using ${tempdir}last_dgdp.dta, type(n:1) unmatch(master)
sort group currency tenor date

global DAY_COUNT 9

* Plot change in cip_govt vs. debt-to-gdp (not netting CB holdings)
twoway (scatter cip_govt_ch gr_dgdp_l if day_count==${DAY_COUNT} & group=="g10" & tenor=="10y", mcolor(navy) msymbol(circle_hollow) mlabel(currency)) ///
       (lfit cip_govt_ch gr_dgdp_l if day_count==${DAY_COUNT} & group=="g10" & tenor=="10y", lcolor(maroon) lwidth(medthick)), ///
       xlabel(0(0.2)2, format(%9.2f) nogrid) ylabel(, nogrid) ///
       xtitle("Debt-to-GDP") ytitle("{&Delta} 10y Government CIP Deviation (bps)") ///
	   title("Government CIP Deviation Response to Reciprocal Tariffs Announcement", size(medium) color(black) bexpand) ///
       legend(off)
graph export "${outdir}figures/tariffs_scatter.eps", replace


*** V. Fig 9: Government debt and swap spreads ***

use $cipdata, clear

gen ss = r - y
gen ss_usd = r_usd - y_usd

gen quarter = qofd(date)
format quarter %tq
sort currency date
keep if tenor=="10y"

collapse (last) group tenor (mean) ss ss_usd, by(currency quarter)
save ${tempdir}ss_non_us, replace

keep if currency == "JPY"
replace ss = ss_usd
replace currency = "USD"

append using ${tempdir}ss_non_us.dta
drop ss_usd

save ${tempdir}ss_panel_q.dta, replace

mmerge currency quarter using ${temp_debt}, type(n:1) unmatch(master)

drop _merge
drop if missing(currency) 

keep currency tenor quarter group ss dgdp_l gr_dgdp_l
keep if group == "g10"

keep if yofd(dofq(quarter)) >= 2010 & yofd(dofq(quarter)) <= 2025

collapse (mean) ss* dgdp_* gr_dgdp_*, by(currency)

twoway lfit ss dgdp_l , lc(maroon) || scatter ss dgdp_l , mlabel(currency) mlabcolor(midblue) mcolor(navy) msymbol(circle_hollow) title("") yti("Swap Spread") xti("Debt/GDP") xla(0(.5)1.5, nogrid) yla(-.2(.2).6, nogrid)  legend(off)   name("scatter_avg", replace)

graph export "${outdir}figures/scatter_avg.eps", replace

twoway lfit ss gr_dgdp_l , lc(maroon) || scatter ss gr_dgdp_l , mlabel(currency) mlabcolor(midblue) mcolor(navy) msymbol(circle_hollow) title("") yti("Swap Spread") xti("Debt/GDP") xla(0(.5)2.0, nogrid) yla(-.2(.2).6, nogrid)  legend(off)   name("scatter_avg_gr", replace)

graph export "${outdir}figures/scatter_avg_gr.eps", replace
